package org.vacoor.xqq.core.msg.handler;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vacoor.xqq.core.msg.chatmsg.*;
import org.vacoor.xqq.core.msg.eventmsg.*;
import org.vacoor.xqq.sound.AudioPlayer;

import java.net.URL;

/**
 * User: vacoor
 */
public class PrintMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(PrintMessageHandler.class);

    @Subscribe
    public void onUnknownMessage(UnknownMsg msg) {
        logger.info("未知消息: {}", msg);
    }

    @Subscribe
    public void onKickMessage(KickMsg msg) {
        logger.info("踢出消息: {}", msg);
    }

    @Subscribe
    public void onContactStatusMessage(StatusChangeMsg msg) {
        logger.info("好友状态改变消息: {}", msg);
    }

    @Subscribe
    public void onShakeMessage(ShakeMsg msg) {
        logger.info("窗口抖动消息: {}", msg);
    }

    @Subscribe
    public void onContactMessage(ContactMsg msg) {
        StringBuilder fragment = new StringBuilder();
        for (MsgElement cf : msg.getMsgBody()) {
            fragment.append(cf);
        }
        logger.info("好友消息: {} (from {})", fragment, msg.getFromUin());
        String m = fragment.toString().trim();
        if(m.startsWith("command:")) {
            executeCommand(m.substring("command:".length()).trim());
        }
        URL url = this.getClass().getClassLoader().getResource("sound/msg.wav");
        AudioPlayer.play(url);
    }

    @Subscribe
    public void onInputNotifyMessage(InputNotifyMsg msg) {
        logger.info("好友输入状态消息: {}", msg);
    }

    @Subscribe
    public void onDiscuMessage(DiscuMsg msg) {
        StringBuilder fragment = new StringBuilder();
        for (MsgElement cf : msg.getMsgBody()) {
            fragment.append(cf);
        }
        logger.info("讨论组消息: {} (from {})", fragment, msg.getFromUin());
    }

    @Subscribe
    @JsonFormat
    public void onGroupMessage(GroupMsg msg) {
        StringBuilder fragment = new StringBuilder();
        for (MsgElement cf : msg.getMsgBody()) {
            fragment.append(cf);
        }
        logger.info("群消息: {} (from {})", fragment, msg.getFromUin());
    }

    public void executeCommand(String command) {
        String[] split = command.split(":");
        if(split.length != 2) {
            return;
        }
        String type = split[0].trim();
        String comm = split[1].trim();
        if( "sys".equals(type) ) {
            if("exit".equals(comm)) {
                System.exit(0);
            }
        }
    }
}
